package com.wt.struggle.goodbye.main.activity

import android.app.Activity
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.support.v7.widget.DividerItemDecoration
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.KeyEvent
import com.google.gson.reflect.TypeToken
import com.wt.struggle.goodbye.R
import com.wt.struggle.goodbye.base.*
import com.wt.struggle.goodbye.info.NetInfo
import com.wt.struggle.goodbye.info.NewsInfo
import com.wt.struggle.goodbye.sq.adapter.PickUserAdapter
import com.wt.struggle.goodbye.user.activity.LoginActivity
import com.wt.struggle.goodbye.user.activity.SiXinOrRecoverActivity
import com.xin.lv.yang.utils.adapter.AdapterCallBack
import kotlinx.android.synthetic.main.head.*
import kotlinx.android.synthetic.main.invitation_details_layout.*
import com.shuyu.gsyvideoplayer.GSYVideoManager
import com.xin.lv.yang.utils.utils.StatusBarUtil

/**
 * 帖子详情 也是帖子列表
 */
class InvitationDetailsActivity : ProActivity() {

    override fun handler(what: Int, arg1: Int, netInfo: NetInfo) {

        when (what) {
            Send.SEARCH_LIST -> {

                refreshView.isRefreshing = false
                removeLoadDialog()
                if (netInfo.code == Config.SUCCESS) {

                    val result = netInfo.dataResult

                    if (result != null && result != "" && result != "null") {
                        val arr = gson!!.fromJson<ArrayList<NewsInfo>>(
                            result,
                            object : TypeToken<ArrayList<NewsInfo>>() {}.type
                        )

                        changeData(arr)

                    } else {
                        showToastShort("无更多数据")
                    }
                }
            }

            Send.COLLECT_CODE -> {

                removeLoadDialog()
                if (netInfo.code == Config.SUCCESS) {
                    val result = netInfo.dataResult
                    if (isCollect == 0) {
                        showToastShort("收藏成功")
                    } else {
                        showToastShort("取消收藏成功")
                    }

                    change()

                }
            }

            Send.IS_LIKE_CODE -> {
                removeLoadDialog()
                if (netInfo.code == Config.SUCCESS) {

                    val result = netInfo.dataResult
                    if (isZan == 0) {
                        showToastShort("点赞成功")
                    } else {
                        showToastShort("您已取消点赞")
                    }

                    change()

                }
            }

            Send.ATTENTION_CODE -> {

                removeLoadDialog()

                if (netInfo.code == Config.SUCCESS) {
                    if (isFoucus == 1) {
                        showToastShort("取消关注成功")
                    } else {
                        showToastShort("关注成功")
                    }

                    change()

                }
            }

        }

    }

    private fun changeData(arr: ArrayList<NewsInfo>) {
        val list = arrayListOf<NewsInfo>()

        for (temp in arr) {
            if (temp.id == newsInfo!!.id) {
                list.add(0, temp)
            } else {
                list.add(temp)
            }
        }

        if (list.size != 0) {

            moreList.addAll(list)

            if (isLoad) {
                /// 加载更多
                adapter.updateData(list)
            } else {
                adapter.updateDataClear(list)
            }

            page++

            tieRecyclerView.scrollToPosition(0)

        }

    }

    private fun change() {
        val info = moreList[clickIndexPosition]
        when (clickCode) {
            1 -> {
                if (info.isCollection == 0) {
                    info.collectionCount++
                    info.isCollection = 1
                } else {
                    if (info.collectionCount != 0) {
                        info.collectionCount--
                        info.isCollection = 0
                    }
                }

            }

            2 -> {
                if (info.isLike == 0) {
                    info.likeCount++
                    info.isLike = 1
                } else {
                    if (info.likeCount != 0) {
                        info.likeCount--
                        info.isLike = 0
                    }
                }
            }

            3 -> {
                info.isDownZan = true
            }

            4 -> {
                info.numberOfCommented = info.numberOfCommented!! + 1
            }

            5 -> {
                if (info.status == 1) {
                    info.status = 0
                } else {
                    info.status = 1
                }
            }

            6 -> {
                /// 改变的用户信息
                val userInfo = info.userExtraInfo

                for (temp in moreList) {
                    val user11 = temp.userExtraInfo
                    if (user11!!.appUserId == userInfo!!.appUserId) {
                        if (user11.isCollection == 0) {
                            user11.isCollection = 1
                        } else {
                            user11.isCollection = 0
                        }
                    }
                }
            }
        }

        adapter.updateByTask(moreList, object : AdapterCallBack<NewsInfo>(list, moreList) {
            override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
                return oldList[oldItemPosition].id == newList[newItemPosition].id
            }

            override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
                return false
            }

            override fun getChangePayload(oldItemPosition: Int, newItemPosition: Int): Any? {
                val bundle = Bundle()
                val oInfo = oldList[oldItemPosition]
                val nInfo = newList[newItemPosition]

                when (clickCode) {
                    1 -> {
                        if (oInfo.isCollection != nInfo.isCollection) {
                            bundle.putParcelable("isCollect", nInfo)
                        }

                    }
                    2 -> {
                        if (oInfo.isLike != nInfo.isLike) {
                            bundle.putParcelable("isLike", nInfo)
                        }

                    }
                    4 -> {
                        if (oInfo.numberOfCommented != nInfo.numberOfCommented) {
                            bundle.putInt("comment", nInfo.numberOfCommented!!)
                        }
                    }
                    6 -> {
                        if (oInfo.userExtraInfo!!.isCollection != nInfo.userExtraInfo!!.isCollection) {
                            bundle.putParcelable("attention", nInfo.userExtraInfo)
                        }

                    }
                }
                return bundle
            }

        })

    }

    var newsInfo: NewsInfo? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContentView(R.layout.invitation_details_layout)

        newsInfo = intent.getParcelableExtra("info")

        if (tvTitle != null) {
            if (newsInfo != null) {
                tvTitle.text = newsInfo!!.circleName
            }

        }

        imageBack.setOnClickListener {
            finish()
        }

        initAdapter()

        refreshView.setOnRefreshListener {
            page = 1
            isLoad = false

            moreList.clear()

            getTieList(newsInfo!!.circleId, newsInfo!!.topicId)

        }

        refreshView.onLoadMore(tieRecyclerView) {
            isLoad = true
            getTieList(newsInfo!!.circleId, newsInfo!!.topicId)

        }

        getTieList(newsInfo!!.circleId, newsInfo!!.topicId)

    }

    var isLoad = false

    var page = 1


    /**
     * 获取帖子列表
     */
    private fun getTieList(circleId: Int, id: Int?) {
        send!!.getSearchList(page, 20, circleId, id!!, 0, "", null, handler!!)
        showLoadDialog("获取中")

    }

    lateinit var adapter: PickUserAdapter

    val list = arrayListOf<NewsInfo>()
    val moreList = arrayListOf<NewsInfo>()

    var clickIndexPosition = -1

    /**
     * 1 为收藏  2 为点赞  3 为不喜欢  4 为评论   5 为关注
     */
    var clickCode = 1
    var isCollect = 0
    var isZan = 0

    var firstVisible = 0

    var isFoucus = 0

    private fun initAdapter() {

        tieRecyclerView.layoutManager = LinearLayoutManager(this)
        tieRecyclerView.addItemDecoration(DividerItemDecoration(this, DividerItemDecoration.VERTICAL))

        adapter = PickUserAdapter(this, list)

        adapter.isEnterCode = 1

        tieRecyclerView.adapter = adapter

        tieRecyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {

            override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)

                if (Build.VERSION.SDK_INT >= 21) {

                    StatusBarUtil.setStatusBarLightMode(window, true)

                }

                val manager = recyclerView!!.layoutManager as LinearLayoutManager
                val firstVisibleItem = manager.findFirstVisibleItemPosition()
                val lastVisible = manager.findLastVisibleItemPosition()

                // 大于0说明有播放
                if (GSYVideoManager.instance().playPosition >= 0) {
                    //当前播放的位置
                    val position = GSYVideoManager.instance().playPosition

                    // 对应的播放列表TAG
                    if (GSYVideoManager.instance().playTag == adapter.TAG &&
                        (position < firstVisibleItem || position > lastVisible)
                    ) {

                        if (GSYVideoManager.isFullState(this@InvitationDetailsActivity)) {
                            return
                        }

                        ///  如果滑出去了上面和下面就是否，和今日头条一样
                        GSYVideoManager.releaseAllVideos()

                    }
                }
            }

            override fun onScrollStateChanged(recyclerView: RecyclerView?, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)

            }
        })


        adapter.itemClickListener = object : ItemClickListener {

            override fun onItemClick(position: Int) {
//
//                val intent = Intent(this@InvitationDetailsActivity, TieDetailsActivity::class.java)
//                intent.putExtra("code", 1)
//                intent.putExtra("data", list[position])
//                startActivity(intent)
//
            }

            override fun onLongClick(position: Int) {

            }

        }

        adapter.onFocusOnClickListener = object : PickUserAdapter.OnFocusOnClickListener {
            override fun onMore(position: Int) {
                openShare(position)
            }

            override fun onFocusOn(position: Int) {

                clickCode = 6
                this@InvitationDetailsActivity.clickIndexPosition = position

                val userInfo = list[position].userExtraInfo
                isFoucus = userInfo!!.isCollection
                send!!.attentionUser(userInfo, handler)
                if (isFoucus == 1) {
                    showLoadDialog("取消中")
                } else {
                    showLoadDialog("关注中")
                }


            }

            override fun onCollect(position: Int) {

                val info = list[position]
                isCollect = info.isCollection!!

                clickCode = 1

                this@InvitationDetailsActivity.clickIndexPosition = position

                /// 收藏帖子
                send!!.collect(info.id.toString(), 1, handler)
                showLoadDialog("收藏中")


            }

            override fun onZan(position: Int) {
                val info = list[position]

                isZan = info.isLike!!

                clickCode = 2
                this@InvitationDetailsActivity.clickIndexPosition = position
                send!!.clickZan(info.id!!, 1, handler)

            }

            override fun onDownZan(position: Int) {
                clickCode = 3

                val intent = Intent(this@InvitationDetailsActivity, SiXinOrRecoverActivity::class.java)
                intent.putExtra("code", 1)
                intent.putExtra("user", list[position].userExtraInfo)
                startActivity(intent)

            }

            override fun onComment(position: Int) {

                clickCode = 4

                this@InvitationDetailsActivity.clickIndexPosition = position

                val iii = Intent(this@InvitationDetailsActivity, CommentListActivity::class.java)

                val info = list[position]

                log("1111------" + info.videoList + "---2222-------" + info.audioList)

                iii.putExtra("info", info)

                iii.putExtra("vvvvList", info.videoList)
                iii.putExtra("audioList", info.audioList)

                startActivity(iii)

            }

        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 234) {
            if (resultCode == Activity.RESULT_OK) {
                adapter.change(clickIndexPosition, clickCode)
            }
        }
    }


    /**
     * 滚动停止播放视频
     */
    fun autoPlayVideo(recyclerView: RecyclerView) {
        val manager = recyclerView.layoutManager as LinearLayoutManager
        val ff = manager.findFirstVisibleItemPosition()

        if (ff > firstVisible) {

            log("执行到此信息信息--------$firstVisible")

            val view = manager.getChildAt(firstVisible)

        }

    }

    /**
     * 打开分享
     */
    fun openShare(adapterPosition: Int) {
        if (Share.getToken(this) != "") {
            val intent = Intent(this, ShareActivity::class.java)
            val info = list[adapterPosition]
            intent.putExtra("info", info)
            intent.putParcelableArrayListExtra("videoList", info.videoList)
            intent.putParcelableArrayListExtra("voiceList", info.audioList)
            intent.putExtra("code", 1)
            startActivity(intent)
        } else {
            startActivity(Intent(this, LoginActivity::class.java))
        }


    }


    override fun onBackPressed() {
        if (GSYVideoManager.backFromWindowFull(this)) {
            return
        }
        super.onBackPressed()
    }

    override fun onPause() {
        super.onPause()
        GSYVideoManager.onPause()
    }


    override fun onDestroy() {
        super.onDestroy()
        GSYVideoManager.releaseAllVideos()
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {

        if (keyCode == KeyEvent.KEYCODE_BACK && event!!.action == KeyEvent.ACTION_DOWN) {

            if (GSYVideoManager.isFullState(this)) {

                GSYVideoManager.backFromWindowFull(this)

            } else {

                finish()

            }

        }

        return super.onKeyDown(keyCode, event)
    }
}